package it.isa.demo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Corgile
 * @date 2022-02-26
 */
@RestController
@RequestMapping(value = "file")
public class FileUploadController {

	@PostMapping(value = "upload")
	public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
		String format = this.getFormat();
		String realPath = request.getServletContext().getRealPath("/img") + format;
		File folder = new File(realPath);
		if (!folder.exists()) {
			System.out.println(folder.mkdirs() ? "创建文件夹成功" : "创建文件夹失败");
		}
		return getUrl(request, format, folder, file);
	}

	@PostMapping(value = "uploads")
	public List<String> uploads(MultipartFile[] files, HttpServletRequest request) throws IOException {
		String format = getFormat();
		String realPath = request.getServletContext().getRealPath("/img") + format;
		File folder = new File(realPath);
		if (!folder.exists()) {
			System.out.println(folder.mkdirs() ? "创建文件夹成功" : "创建文件夹失败");
		}
		List<String> urls = new ArrayList<>();
		for (MultipartFile file : files) {
			urls.add(getUrl(request, format, folder, file));
		}
		urls.forEach(System.out::println);
		return urls;
	}

	// TODO : 根据需求调整文件夹类型格式
	private String getFormat() {
		return new SimpleDateFormat("/yyyy/MM-dd/").format(new Date());
	}

	private String getUrl(HttpServletRequest request,
						  String format, File folder,
						  MultipartFile file)
			throws IOException {
		String oldName = file.getOriginalFilename();
		assert oldName != null;
		String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
		file.transferTo(new File(folder, newName));
		return request.getScheme() + "://" + request.getServerName() + ":"
				+ request.getServerPort() + "/img" + format + newName;
	}

}
